import { Card, message, Row, Col, Space } from 'antd';
import { history } from 'umi';
import ProForm, {
  ProFormSelect,
  ProFormTextArea,
  ProFormText,
  ProFormDateRangePicker,
  ProFormUploadButton,
} from '@ant-design/pro-form';
import { useRequest } from 'umi';
import type { FC } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { fakeSubmitForm, queryDetail, update, queryProvince } from './service';
// import RichText from '@/components/RichText';

const BasicForm: FC<Record<string, any>> = () => {
  const { run } = useRequest(fakeSubmitForm, {
    manual: true,
    onSuccess: () => {
      history.push('/activity/activity-list');
      message.success('提交成功');
    },
  });

  const onFinish = async (values: Record<string, any>) => {
    if (values.backgroundFile[0].response) {
      let filesUrl = '';
      for (var i = 0; i < values.backgroundFile.length; i++) {
        filesUrl += values.backgroundFile[i].response.data.url + ',';
      }
      values.background = filesUrl.substring(0, filesUrl.length - 1);
      delete values.backgroundFile;
    }
    if (values.sponsorUpload[0].response) {
      let filesUrl = '';
      for (var i = 0; i < values.sponsorUpload.length; i++) {
        filesUrl += values.sponsorUpload[i].response.data.url + ',';
      }
      values.sponsor = filesUrl.substring(0, filesUrl.length - 1);
      delete values.sponsorUpload;
    }
    if (values.dateRange) {
      values.startTime = values.dateRange[0];
      values.endTime = values.dateRange[1];
      delete values.dateRange;
    }
    if (values.province) {
      values.provinceCode = values.province.value;
      values.provinceName = values.province.label;
      delete values.province;
    }
    console.log('values', values);
    if (history.location.query.id) {
      values.id = history.location.query.id;
      try {
        const response = await update(values);
        if (response.code == 200) {
          history.push('/activity/activity-list');
          message.success('修改成功');
        } else {
          message.error('修改失败!');
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      run(values);
    }
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 8 },
  };

  return (
    <PageContainer content="">
      <Card bordered={false}>
        <ProForm
          hideRequiredMark
          style={{ margin: 'auto', marginTop: 8 }}
          name="basic"
          layout="horizontal"
          // initialValues={data}
          onFinish={onFinish}
          {...formItemLayout}
          request={async () => {
            if (history.location.query.id) {
              return queryDetail(history.location.query).then(({ data }) => {
                if (data.background) {
                  data.backgroundFile = [
                    {
                      uid: '1',
                      name: 'icon',
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + data.background,
                    },
                  ];
                }
                if (data.sponsor) {
                  data.sponsorUpload = [
                    {
                      uid: '1',
                      name: 'icon',
                      status: 'done',
                      url: 'http://oss.yizuoyiyou.com.cn' + data.sponsor,
                    },
                  ];
                }
                data.type = data.type + '';
                data.dateRange = [];
                data.dateRange[0] = data.startTime;
                data.dateRange[1] = data.endTime;
                console.log('data', data);
                let province = {};
                province.value = data.provinceCode;
                province.label = data.provinceName;
                data.province = province;
                console.log('data', data);
                return data;
              });
            } else {
              return {};
            }
          }}
          submitter={{
            render: (props, doms) => {
              return (
                <Row>
                  <Col span={14} offset={4}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              );
            },
          }}
        >
          <ProFormText
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '请输入标题',
              },
            ]}
            placeholder="请输入标题"
          />
          <ProFormTextArea name="info" label="简介" placeholder="请输入简介" />
          <ProFormUploadButton
            name="backgroundFile"
            label="活动背景图"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
          />
          <ProFormSelect
            fieldProps={{
              labelInValue: true,
            }}
            label="活动归属地"
            name="province"
            request={async () => {
              return queryProvince().then(({ data }) => {
                return data.map((item, index) => {
                  return {
                    label: item.name,
                    value: item.code,
                  };
                });
              });
            }}
          />
          <ProFormText
            label="明细"
            name="articleId"
            rules={[
              {
                required: true,
                message: '请输入活动文章id',
              },
            ]}
            placeholder="请输入活动文章id"
          />
          {/* {history.location.query.id != undefined ? (
            <ProFormSelect
              name="status"
              label="状态"
              rules={[
                {
                  required: true,
                  message: '请选择活动状态!',
                },
              ]}
              options={[
                {
                  label: '未开始',
                  value: '0',
                },
                {
                  label: '进行中',
                  value: '1',
                },
                {
                  label: '暂停中',
                  value: '2',
                },
                {
                  label: '已结束',
                  value: '3',
                },
              ]}
            />
          ) : null} */}
          <ProFormSelect
            name="type"
            label="类型"
            // fieldProps={{
            //   mode: 'multiple',
            //   labelInValue: true,
            // }}
            options={[
              {
                label: '病历大赛',
                value: '1',
              },
            ]}
          />
          <ProFormSelect
            fieldProps={{
              labelInValue: true,
            }}
            label="可参与省份（选填）"
            name="province"
            request={async () => {
              return queryProvince().then(({ data }) => {
                return data.map((item, index) => {
                  return {
                    label: item.name,
                    value: item.code,
                  };
                });
              });
            }}
          />
          <ProFormDateRangePicker
            name="dateRange"
            label="有效期"
            fieldProps={{
              style: {
                width: '100%',
              },
            }}
          />
          <ProFormTextArea name="guidance" label="指导单位" placeholder="请输入指导单位" />
          <ProFormTextArea name="host" label="主办单位" placeholder="请输入主办单位" />
          <ProFormTextArea name="jointlyHost" label="联合主办" placeholder="请输入联合主办" />
          <ProFormTextArea name="coOrganizer" label="协办单位" placeholder="请输入协办单位" />
          <ProFormTextArea name="organizer" label="承办单位" placeholder="请输入承办单位" />
          {/* <ProForm.Item label="赞助单位" name="content">
            <RichText />
          </ProForm.Item> */}
          <ProFormUploadButton
            name="sponsorUpload"
            label="赞助单位"
            max={1}
            fieldProps={{
              name: 'file',
              listType: 'picture-card',
            }}
            action="/api/file/upload"
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};

export default BasicForm;
